//
//  JLAddJLViewController.m
//  Estate
//
//  Created by heyong on 16/6/2.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "JLAddJLViewController.h"
#import "DefaineCell.h"
#import "selectBtnCell.h"
#import "PositionTableCell.h"
#import "B_wuLiaoCell.h"
#import "QianDTableCell.h"
#import "OrientationViewController.h"
#import "recordTypeModel.h"

@interface JLAddJLViewController ()
@property (strong, nonatomic) FMDatabase *db;

@property(strong, nonatomic)NSMutableArray  *arr;

// block参数
@property (strong, nonatomic) PositionBlockModel *blockModel;
// 当前被点的地址数据模型
@property (strong, nonatomic) AddressModel *addressModel;

@end

@implementation JLAddJLViewController

-(NSMutableArray *)weatherArr{
    if(_weatherArr==nil){
        _weatherArr=[NSMutableArray array];
    }
    return _weatherArr;
}

-(NSMutableArray *)arr{
    if (!_arr) {
        _arr = [NSMutableArray array];
    }
    return _arr;
}
- (NSMutableArray *)selectedAssetURLs{
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

-(TPKeyboardAvoidingTableView *)tableView{
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:self.view.bounds];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [_tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qCell"];
        [_tableView registerClass:[selectBtnCell class] forCellReuseIdentifier:@"sCell"];
        [_tableView registerClass:[PositionTableCell class] forCellReuseIdentifier:@"pCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaine"];
        [_tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

-(FMDatabase *)db{
    if(_db==nil){
        _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    }
    return _db;
}

- (UIImagePickerController *)picker{
    if(!_picker){
        _picker = [[UIImagePickerController alloc] init];
        _picker.delegate = self;
        _picker.allowsEditing = NO;//设置可编辑
        _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _picker;
}

// 重写setter方法 赋值
- (void)setRecordId:(NSString *)recordId{
    _recordId=recordId;
    DBHelper *helper=[DBHelper help];
    NSDictionary *dic=[[helper DataBase:
                        self.db selectKeyTypes:@{@"RECORD_TYPE":@"text",
                                                 @"RECORD_USER":@"text",
                                                 @"RECORD_TITLE":@"text",
                                                 @"RECORD_FILE_PATH":@"text",
                                                 @"ADDRESS_ID":@"text",
                                                 @"ADDRES_INFO":@"text",
                                                 @"RECORDONTENT":@"text",
                                                 @"EXTEND_INFO":@"text",
                                                 @"PRO_ID":@"text",
                                                 @"WEATHER":@"text",
                                                 @"CREATE_TIME":@"text"
                                                 }fromTable:WORK_RECORD
                         whereCondition:@{@"ID":recordId}]lastObject];
    
    _record=[[record alloc]init];
    _record.proName=DEFISNUL([LSUtility getProjectNameByProjectId:dic[@"PRO_ID"]][@"PROJECT_NAME"]);
    _record.positionId=DEFISNUL(dic[@"ADDRESS_ID"]);
    _record.positionInfo=DEFISNUL(dic[@"ADDRES_INFO"]);
    
    NSDictionary *exDic=DEFISNUL([LSUtility dictionaryWithJsonString:dic[@"EXTEND_INFO"]];
    _record.extendInfo=exDic[@"address"]);
    _record.position=DEFISNUL([LSUtility getAddressNameByAddressId:_record.positionId][@"ADDRESS_NAME" ]);
    
    _record.type=DEFISNUL(dic[@"RECORD_TYPE"]);
    _record.recordName=DEFISNUL([LSUtility getuserIdByUserName:dic[@"RECORD_USER"]][@"REAL_NAME"]);
    _record.time=DEFISNUL(dic[@"CREATE_TIME"]);
    NSArray *wearArr=[dic[@"WEATHER"] componentsSeparatedByString:@"/"];
    _record.address=DEFISNUL([wearArr firstObject]);
    _record.weather=DEFISNUL([wearArr lastObject]);
    _record.title=DEFISNUL(dic[@"RECORD_TITLE"]);
    _record.content=DEFISNUL(dic[@"RECORDONTENT"]);
    _record.recordFilePath=DEFISNUL(dic[@"RECORD_FILE_PATH"]);
    
    //设置附件
    NSArray *imageArr=[LSUtility dictionaryWithJsonString:_record.recordFilePath];
    
    //查询附件表
    if(imageArr.count>0){
        for (NSDictionary *imageDic in imageArr) {
            NSString *fileId=imageDic[@"fileId"];
            NSString *fileName=[LSUtility queryAttachment:fileId][@"FILE_NAME"];
            //            NSLog(@"---%@",fileName);
            NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                                [NSString stringWithFormat:@"/%@",fileName]];
            [self.selectedAssetURLs addObject:filePath];
        }
    }
    self.curTweet.selectedAssetURLs =self.selectedAssetURLs;
    //判断能否编辑
    if([self.flag isEqualToString:@"look"]){
        self.isEdit=NO;
    }else{
        self.isEdit=[LSUtility isSameDay:_record.time andRecordId:_recordId];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"记录";
    _curTweet = [[Tweet alloc] init];
    [self.view addSubview:self.tableView];
    if(self.isEdit){
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    }
    //天气数组
    NSMutableArray *wArr = DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
    if(wArr.count>0){
        for (NSDictionary *wdic in wArr) {
            for (NSString *city in wdic) {
                [self.weatherArr addObject:city];
            }
        }
    }
    [self setData];
    [self refresh:nil];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage" object:nil];
}

- (void)refresh:(id)sender{
    if(self.selectedAssetURLs!=nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs =self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
}

- (void)setData{
    //如果为空设置默认值
    if(_recordId==nil){
        _record=[[record alloc]init];
        //天气数组
        NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
        _record.address=[self.weatherArr firstObject];
        _record.weather=[[wArr firstObject]objectForKey:_record.address];
        _record.proName=DEF_PERSISTENT_GET_OBJECT(@"proname");
        _record.positionId=self.locationId;
        _record.positionInfo=DEFISNUL(self.addressInfo);
        _record.extendInfo=DEFISNUL(self.locations);
        _record.type=DEFISNUL(self.define);
        _record.recordName=DEF_PERSISTENT_GET_OBJECT(@"realname");
        _record.time=[LSUtility nowTime];
        _record.title=@"";
        _record.content=@"";
        _record.recordFilePath=@"";
        //默认巡视
        _record.type=@"RECORD_01";
    }
}

#pragma mark--保存
- (void)clickSave {
    if ([self.flag isEqualToString:@"add"]) {
        for (NSString *path in self.selectedAssetURLs) {
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            NSArray *strArray = [path componentsSeparatedByString:@"/"];
            if (strArray) {
                //存入附件永久文件夹
                [LSUtility saveImagePermanent:image withName:[strArray lastObject]];
            }
        }
        [self addDataBase];
    }else{
        [self updateDataBase];
    }
}

#pragma mark -数据操作
- (void)addDataBase{
    
    if(_record.positionId==nil||[_record.positionId isEqualToString:@""]){
        [LSUtility showToastWithMessage:@"请选择位置" inView:self.view Andtime:1.];
        return;
    }
    if([_record.title isEqualToString: @""]){
        [LSUtility showToastWithMessage:@"请输入标题" inView:self.view Andtime:1.];
        return;
    }
    if([_record.type isEqualToString:@""]){
        [LSUtility showToastWithMessage:@"请选择类型" inView:self.view Andtime:1.];
        return;
    }
    if([_record.content isEqualToString:@""]){
        [LSUtility showToastWithMessage:@"请输入内容" inView:self.view Andtime:1.];
        return;
    }
    if ([[[UITextInputMode currentInputMode]primaryLanguage] isEqualToString:@"emoji"])
    {
        //@“不支持emoji表情输入";
        [LSUtility showToastWithMessage:@"不支持emoji表情输入" inView:self.view Andtime:1.];
        
        return ;
    }
    
    /*
     *  附件表新增数据
     */
    //记录表id
    NSString *fileId=[NSUUID UUID].UUIDString;
    
    self.curTweet.selectedAssetURLs = [ self.curTweet.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    //循环存入附件表
    if(self.curTweet.selectedAssetURLs.count>0){
        //附件表id
        for (int i=0; i<self.curTweet.selectedAssetURLs.count; i++) {
            NSString *ids=[NSUUID UUID].UUIDString;
            NSArray *arr=[self.curTweet.selectedAssetURLs[i] componentsSeparatedByString:@"/"];
            NSString *imageName = [arr lastObject];
//            UIImage *image=[UIImage imageWithContentsOfFile:self.curTweet.selectedAssetURLs[i]];
            //存入附件表
            [LSUtility insertAttachmentFromFileID:fileId andTableID:ids andImage:nil andType:_record.type andImageName:imageName];
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            
            [dict setObject:ids forKey:@"fileId"];
            
            [dict setObject:@"1" forKey:@"fileState"];
            
            [self.arr addObject:dict];
        }
        //附件上传
        //        DataSynchronization  *sync=[[DataSynchronization alloc]init];
        //        [sync uploadAttachsBackground];
    }
    /*
     *  记录表新增数据
     */
    NSString *weather=[NSString stringWithFormat:@"%@/%@",DEFISNUL(_record.address),DEFISNUL(_record.weather)];
    
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if([role isEqualToString:@"USER_01"]){
        role=@"0";
    }else if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]){
        role=@"1";
    }
    
    NSDictionary *dic=@{
                        @"ID":fileId,
                        @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                        @"RECORD_USER":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                        @"RECORD_MASTER":@"",
                        @"RECORD_SUPERVISION_USER":@"",
                        @"WEATHER":weather,
                        @"ADDRESS_ID":_record.positionId,
                        @"ADDRES_INFO": _record.positionInfo,
                        @"RECORD_TYPE":_record.type,
                        @"RECORD_TITLE":_record.title,
                        @"RECORDONTENT":_record.content,
                        @"RECORD_FILE_PATH":DEFISNUL([LSUtility dictionaryToJson:self.arr]),
                        @"RECORD_INFO":@"",
                        @"STATE":role,
                        @"RECORD_NUMBER":@"",
                        @"EXTEND_INFO":[LSUtility dictionaryToJson_2:@{@"address":_record.extendInfo ,@"map":@{}}],
                        @"MODIFY_USER_NAME":@"",
                        @"MODIFY_IP":@"",
                        @"MODIFY_TIME":@"",
                        @"CREATE_USER_NAME":@"anonymous",
                        @"CREATE_TIME":[LSUtility nowTime],
                        @"CREATE_IP":[LSUtility getIPAddress],
                        @"LOCAL_MODIFY_STATE":@"ADD",
                        @"LOCAL_MODIFY_USER_NAME":@"",
                        @"LOCAL_MODIFY_TIME":@""
                        };
    
    DBHelper *helper=[DBHelper help];
    BOOL isOk=[helper DataBase:self.db insertKeyValues:dic intoTable:WORK_RECORD];
    
    if(isOk){
        NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_jl" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        NSNotification * notice2 = [NSNotification notificationWithName:@"Refresh_zj_jl" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice2];
        
    }else{
        [MBProgressHUD showError:@"添加失败" toView:self.view];
    }
    
    if(self.define){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma  mark - 修改数据
- (void)updateDataBase{
    /*
     *附件表修改
     */
    //循环存入附件表
    self.curTweet.selectedAssetURLs = [ self.curTweet.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    if(self.curTweet.selectedAssetURLs.count>0){
        //附件表id
        for (int i=0; i<self.curTweet.selectedAssetURLs.count; i++) {
            NSString *ids=[NSUUID UUID].UUIDString;
            
            NSArray *arr=[self.curTweet.selectedAssetURLs[i] componentsSeparatedByString:@"/"];
            
            NSString *imageName = [arr lastObject];
            
            UIImage *image=[UIImage imageWithContentsOfFile:self.curTweet.selectedAssetURLs[i]];
            
            //存入附件表
            [LSUtility insertAttachmentFromFileID:_recordId andTableID:ids andImage:image andType:_record.type andImageName:imageName];
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            
            [dict setObject:ids forKey:@"fileId"];
            
            [dict setObject:@"1" forKey:@"fileState"];
            
            [self.arr addObject:dict];
        }
    }
    
    /*
     *  记录表修改数据
     */
    NSString *weather=[NSString stringWithFormat:@"%@/%@",DEFISNUL(_record.address),DEFISNUL(_record.weather)];
    NSLog(@"weather:%@",weather);
    
    NSDictionary *dics=@{
                         @"WEATHER":weather,
                         @"ADDRESS_ID":_record.positionId,
                         @"ADDRES_INFO":_record.positionInfo,
                         @"RECORD_TYPE":_record.type,
                         @"RECORD_TITLE":_record.title,
                         @"RECORDONTENT":_record.content,
                         @"RECORD_FILE_PATH":DEFISNUL([LSUtility dictionaryToJson:self.arr]),
                         @"MODIFY_USER_NAME":USERID,
                         @"EXTEND_INFO":[LSUtility dictionaryToJson_2:@{@"address":_record.extendInfo ,@"map":@{}}],
                         @"MODIFY_TIME":[LSUtility nowTime],
                         @"MODIFY_IP":[LSUtility getIPAddress],
                         @"LOCAL_MODIFY_STATE":@"MOD",
                         };
    
    
    
    DBHelper *helper=[DBHelper help];
    
    [helper DataBase:self.db updateTable:WORK_RECORD setKeyValues:dics whereCondition:@{@"ID":_recordId}];
    
    NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_jl" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    
    NSNotification * notice2 = [NSNotification notificationWithName:@"Refresh_zj_jl" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice2];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma  mrak--UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    if(section==0){
        if(row==0){
            return 40;
        }
        return 44;
    }else if(section==1){
        if(row==0){
            return 44;
        }else{
            return 120;
        }
    }else{
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件"];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 0.001;
    }else{
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 8;
    }else if (section==1){
        return 2;
    }else{
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    long section=indexPath.section;
    long row=indexPath.row;
    
    if(section==0){
        
        if(row==0){
            
            TableTopStateCell *cell=[tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
            if(![self.flag isEqualToString:@"add"]){
                cell.title.text=[NSString stringWithFormat:@"%@  现场录入",_record.time];
            }else{
                cell.title.text=[NSString stringWithFormat:@"%@  现场录入",[LSUtility dateNow]];
            }
            
            return cell;
            
        }else if(row==1){
            
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            cell.textLeadCinstraint.constant=20.;
            cell.title.text=@"项   目:";
            cell.text.text=_record.proName;
            
            return  cell;
            
        }else if(row==2){
            
            PositionTableCell *cell =[tableView dequeueReusableCellWithIdentifier:@"pCell" forIndexPath:indexPath];
            cell.isEdit=self.isEdit;
            
            if(_record.extendInfo==nil||[_record.extendInfo isEqualToString:@""]){
                cell.btnStr=@"请选择位置";
                
            }else{
                NSDictionary *dic = [LSUtility dictionaryWithJsonString:_record.positionInfo ];
                cell.btnStr = [NSString stringWithFormat:@"%@ %@",dic[@"address"],dic[@"leftDistanceStr"]];
            }
            
            cell.cliclWzBlock = ^{
                
                OrientationViewController *location=[[OrientationViewController alloc]init];
                location.flagStr = @"jilu";
                location.dataArr1 = [NSMutableArray arrayWithArray:self.blockModel.dataArr1];
                location.dataArr2 = [NSMutableArray arrayWithArray:self.blockModel.dataArr2];
                location.dataArr3 = [NSMutableArray arrayWithArray:self.blockModel.dataArr3];
                location.dataArr4 = [NSMutableArray arrayWithArray:self.blockModel.dataArr4];
                location.addressArr = [NSMutableArray arrayWithArray:self.blockModel.addressArr];

                location.aID = self.blockModel.aID;
                location.firstID = self.blockModel.firstID;
                location.secondID = self.blockModel.secondID;
                location.thirdID = self.blockModel.thirdID;
                location.keyStr = self.blockModel.keyStr;
                location.number = self.blockModel.number;
                location.position = self.blockModel.position;
                location.addressModel = self.addressModel;
                
                if(_record.positionInfo){
                    NSDictionary *dic=[LSUtility dictionaryWithJsonString:_record.positionInfo];
                    CGFloat x=[dic[@"long"] floatValue];
                    CGFloat y=[dic[@"lat"] floatValue];
                    location.selectedX=x;
                    location.selectedY=y;
                }
                
                if(_record.positionId){
                    location.number = 2;
                }
//                location.selectedX = self.blockModel.selectedX;
//                location.selectedY = self.blockModel.selectedY;
                location.scale = self.blockModel.scale;
                if (location.number) {
                    location.hC = YES;
                    location.firstID=@"";
                    location.aID=_record.positionId;               
                }
                [self.navigationController pushViewController:location animated:YES];
                
                // 回传位置值
                location.returnPlaceInfoBlock = ^(PositionBlockModel *model, AddressModel *addModel, NSString *addInfoStr){
                    self.blockModel = model;
                    self.addressModel = addModel;
                    
                    _record.extendInfo = model.keyStr;
                    _record.positionInfo = addInfoStr;
                    _record.positionId = model.aID;
                    [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                };
            };
            return cell;
            
        }else if(row==3){
            
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
           
            
            [cell setTitle:@"类   型:" andDetail:_record.type andLeftConstraint:20.];
            
            return cell;
            
        }else if(row==4){
            
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            [cell setTitle:@"记录人:" andDetail:_record.recordName andLeftConstraint:20.];
            
            return  cell;
            
        }else if (row==5){
            
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            [cell setTitle:@"时   间:" andDetail:_record.time andLeftConstraint:20.];
            
            return  cell;
            
        }else if (row==6){
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            [cell setTitle:@"地   区:" andDetail:_record.address andLeftConstraint:20.];
            return  cell;
        }else{
            
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            
            [cell setTitle:@"天   气:" andDetail:_record.weather andLeftConstraint:20.];
            
            return  cell;
        }
    }else if (section==1){
        
        if(row==0){
            
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
            
            cell.textValueChangedBlock=^(NSString *values){
                _record.title=values;
            };
            [cell configWithPlaceholder:@"请输入标题" andValue:_record.title andLabel:@"标   题:" andKeyType:UIKeyboardTypeDefault];
            cell.isedit=self.isEdit;
            
            return cell;
            
        }else{
            
            B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            
            cell.textValueChangedBlock=^(NSString *value){
                _record.content=value;
            };
            
            [cell setTitle:@"内   容:" andPlaceHolder:@"请输入内容" andTextValue:_record.content];
            
            cell.isEdit=weakSelf.isEdit;
            
            return cell;
        }
    }else{
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.isEdit=self.isEdit;
        [cell setTitle:@"附件信息"];
        [cell setTitleColor:[UIColor colorWithRed:0.22 green:0.64 blue:0.59 alpha:1.00]];
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        
        cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
            // 移除图片
            [weakSelf.curTweet deleteATweetImage:toDelete];
            // 移除数组
            [weakSelf.selectedAssetURLs removeObject:deUrl];
            
            [weakSelf refresh:nil];
        };
        return cell;
    }
}

/*
 *点击方法
 */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    if(weakSelf.isEdit){
        if(indexPath.section==0){
            //新需求 记录增加类型
            if(indexPath.row==3){
                NSArray *array=[NSArray arrayWithArray:RECORDTYPE.recordTypeArray];
                NSNumber *ninit = [NSNumber numberWithInteger:0];
                
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[array] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                    int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                    NSString *typeStr =array[iv];
                    
                    _record.type=[RECORDTYPE.recordTypeDic objectForKey:typeStr];
                    //刷新行
                    NSIndexPath *windexPath=[NSIndexPath indexPathForRow:3 inSection:0];
                    [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath,windexPath] withRowAnimation:UITableViewRowAnimationNone];
                    
                } cancelBlock:nil origin:self.view];
            }
            
            if(indexPath.row==6){
                NSNumber *ninit = [NSNumber numberWithInteger:0];
                
                NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
                if(!wArr){
                    wArr=[NSMutableArray arrayWithObject:@{@"无":@"暂时无法获得天气信息"}];
                }
                if(self.weatherArr.count<1){
                    [self.weatherArr addObject:@"无"];
                }
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[self.weatherArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                    int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                    NSDictionary *weadic=wArr[iv];
                    NSString *address =self.weatherArr[iv];
                    
                    _record.address=address;
                    _record.weather=weadic[address];
                    //刷新城市、刷新天气
                    NSIndexPath *windexPath=[NSIndexPath indexPathForRow:7 inSection:0];
                    [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath,windexPath] withRowAnimation:UITableViewRowAnimationNone];
                    
                } cancelBlock:nil origin:self.view];
            }
        }
    }
    
}

#pragma mark UIActionSheet M

- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (_curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
    
        [self presentViewController:self.picker animated:YES completion:nil];//进入照相界面
        
    }else if (buttonIndex == 1){
        
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages = [[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
            for (NSString *path in array) {
                //添加图片路径到已选数组
                [self.selectedAssetURLs addObject:path];
            }
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        //刷新指定行
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark scrollview

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

@end




